const canvas = document.querySelector("#canvas");
const context = canvas.getContext("2d");
const image = new Image();

let originalImageData;
let interval;

function increaseTransparency(imageData, steps) {
    const { data } = imageData;
    const { length } = data;
    let alpha, currentAlpha, step;
    let i = 3;
    for (let i = 3; i < length; i += 4) {
        alpha = originalImageData.data[i];
        if (alpha > 0 && data[i] > 0) {
            currentAlpha = data[i];
            step = Math.ceil(alpha / steps);
            if (currentAlpha - step > 0) {
                data[i] -= step;
            } else {
                data[i] = 0;
            }
        }
    }
}

function fadeOut(context, imageData, x, y, steps, millisecondsPerStep) {
    let frame = 0;
    interval = setInterval(() => {
        frame++;
        if (frame > steps) {
            clearInterval(interval);
            animationComplete();
        } else {
            increaseTransparency(imageData, steps);
            context.putImageData(imageData, x, y);
        }
    }, millisecondsPerStep);
}

function animationComplete() {
    setTimeout(() => {
        context.drawImage(image, 0, 0, canvas.width, canvas.height);
    }, 1000);
}

image.src = "./pic.png";
image.onload = () => {
    context.drawImage(image, 0, 0, canvas.width, canvas.height);
    originalImageData = context.getImageData(0, 0, canvas.width, canvas.height);
    setTimeout(() => {
        fadeOut(
            context,
            context.getImageData(0, 0, canvas.width, canvas.height),
            0,
            0,
            20,
            1000 / 60
        );
    }, 1000);
};
